const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');

const root = process.cwd();
// 获取终端输入信息
const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});
const getReadline = (question) => {
  return new Promise((resolve) => {
    readline.question(question, resolve);
  });
};
// 更新版本号
const updateVersionHandler = () => {
  const packageJsonStr = fs
    .readFileSync(path.resolve(root, './package.json'))
    .toString();
  const packageJson = JSON.parse(packageJsonStr) || {};
  let [max, mid, min] = (packageJson.version || '').split('.');
  if (Number(min) < 9) {
    min = Number(min) + 1;
  } else if (Number(mid) < 9) {
    mid = Number(mid) + 1;
    min = 0;
  } else {
    max = Number(max) + 1;
    mid = 0;
    min = 0;
  }
  const version = [max, mid, min].join('.');
  packageJson.version = version;
  fs.writeFileSync(
    path.resolve(root, './package.json'),
    JSON.stringify(packageJson),
  );
  execSync('npx prettier --write package.json');
  return Promise.resolve(version);
};

const mainHanlder = async () => {
  try {
    // 是否需要更新版本号
    const versionMessage = await getReadline(
      '是否更新版本号，作用于发布npm(y/n)? ',
    );
    const wordMessage = await getReadline(
      '是否构建组件库文档包并提交到git仓库(y/n)? ',
    );
    const gitMessage = await getReadline(
      '代码提交信息，不输入则不提交，注意提交规范： ',
    );
    readline.close();
    console.log('组件库包构建开始...');
    execSync('npx father doctor');
    execSync('npx father build');
    console.log('组件库包构建完成!');
    if (versionMessage === 'y') {
      const version = await updateVersionHandler();
      console.log('版本号更新完成(' + version + ')!');
    }
    if (Boolean(gitMessage)) {
      console.log('代码提交开始...');
      execSync('git add .');
      execSync('git commit -m "' + gitMessage + '"');
      execSync('git push');
      console.log('代码提交完成!');
    }
    if (wordMessage === 'y') {
      console.log('组件库文档包构建开始...');
      execSync('npx dumi build');
      console.log('组件库文档包构建完成!');
      console.log('组件库文档包提交开始...');
      execSync('npx gh-pages -d docs-dist');
      console.log('组件库文档包提交完成!');
    }
  } catch (error) {
    console.log('构建部署提交等操作失败', error);
    process.exit(1);
  }
};
mainHanlder();
